<?php

namespace app\cashdesk\controller;

use app\common\controller\Frontend;
use fast\Random;
use think\Db;
use think\Exception;
use think\Session;
use think\exception\HttpResponseException;
use think\Response;
use think\Config;

class Index extends Frontend
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';
    //商品分类父级id
    protected $goods_pid = 104;
    //服务分类父级id
    protected $service_pid = 105;
    //卡项分类id
    protected $card_pid = 1;
    //用户模型
    protected $user_model = null;
    //用户等级模型
    protected $user_group_model = null;
    //用户资金变动表
    protected $user_money_log_model = null;

    //商品模型
    protected $goods_model = null;
    //商品Sku模型
    protected $goods_sku_model = null;

    //商品分类模型
    protected $goods_category_model = null;
    //卡项模型
    protected $card_category_model = null;
    //服务人员模型
    protected $staff_model = null;

    //卡项分类数据
    protected $card_type_arr = null;
    protected $card_type_name_arr = null;
    
    //会员优惠券
    protected $user_coupon_model = null;
    protected $coupon_model = null;
    
    //支付模型
    protected $pay_model = null;

    //权益卡信息
    protected $item_model = null;

    //权益卡详情信息
    protected $item_info_model = null;

    //权益卡模型
    protected $order_item_model = null;

    //权益卡订单模型
    protected $order_item_info_model = null;
    
    //充值卡续卡模型
    protected $order_item_recharge_model = null;

    //权益卡使用记录模型
    protected $order_item_pay_model = null;

    //订单模型
    protected $order_model = null;

    //商品订单模型
    protected $goods_order_model = null;
    
    //商铺模型
    protected $shop_model = null;
    
    //支付模型
    protected $pay_out_trade_model = null;
    protected $wanlshop_pay_model = null;
    protected $goods_shop_model = null;

    protected $shop_id = null;

    public function _initialize(){
        $adminshop = Session::get('adminshop');
        $shop = Session::get('shop');

        if (!empty($adminshop) && !empty($shop)) {
            $this->shop_id = $shop;
        }else{
            $this->redirect('/fQTrLEivaP.php');
            // $this->shop_id = 1;
        }

        $this->user_model = new \app\admin\model\User;
        $this->user_group_model = new \app\admin\model\UserGroup;
        $this->user_money_log_model = new \app\index\model\wanlshop\Money;
        $this->goods_model = new \app\admin\model\wanlshop\Goods;
        $this->goods_sku_model = new \app\admin\model\inventory\Sku;
        $this->goods_category_model = new \app\admin\model\wanlshop\Category;
        $this->card_category_model = new \app\admin\model\item\Item;
        $this->staff_model = new \app\admin\model\Staff;
        $this->coupon_model = new \app\admin\model\wanlshop\Coupon;
        $this->user_coupon_model = new \app\admin\model\wanlshop\CouponReceive;
        $this->pay_model = new \app\common\model\Pay;
        $this->item_model = new \app\admin\model\item\Item;
        $this->item_info_model = new \app\admin\model\item\ItemInfo;
        $this->order_item_model = new \app\admin\model\order\Item;
        $this->order_item_info_model = new \app\admin\model\order\ItemInfo;
        $this->order_item_recharge_model = new \app\admin\model\order\ItemRecharge;
        $this->order_item_pay_model = new \app\admin\model\order\ItemPay;
        $this->order_model = new \app\admin\model\wanlshop\Order;
        $this->goods_order_model = new \app\admin\model\order\Goods;
        $this->shop_model = new \app\admin\model\store\Shop;
        $this->pay_out_trade_model = new \app\api\model\wanlshop\PayOutTrade;
        $this->wanlshop_pay_model = new \app\admin\model\wanlshop\Pay;
        $this->goods_shop_model = new \app\admin\model\wanlshop\GoodsShop;
        // $this->card_type_name_arr = ['有限次卡','不限次卡','通卡','充值卡','折扣卡'];
        $this->card_type_name_arr = ['有限次卡','不限次卡','通卡','充值卡','折扣卡','续卡'];

        for ($i=1; $i <=6 ; $i++) { 
            $this->card_type_arr[] = ['id' => $i, 'name' => $this->card_type_name_arr[$i-1]];
        }
    }

    public function orderRefund(){
        $refundPrice = $this->request->param('refund_price');
        $itemId = $this->request->param('order_item_id');
        $note = $this->request->param('note');
        $order = Db::name('wanlshop_order_item i')
            ->join('wanlshop_order o', 'i.order_id = o.id', 'left')
            ->join('wanlshop_pay_out_trade t', 'o.id = t.order_id', 'left')
            ->field('o.user_id,o.shop_id,o.id,o.order_no,t.pay_way_id,i.type')
            ->where(['i.id'=>$itemId])
            ->find();
        $req_params =[];
        $req_params['order_no'] =$order['order_no'];
        $req_params['refund_price'] =$refundPrice;

        if(in_array($order['pay_way_id'],[10,12]) && $req_params['refund_price']>0){
            $req_url = cdnurl('/api/Member/refundV2',true);//拉卡拉退款接口

            write_log_record("[".date("Y-m-d H:i:s")."]退款接口参数33333：".json_encode($req_params));
            $result = send_request($req_url, json_encode($req_params),'POST');
            write_log_record("[".date("Y-m-d H:i:s")."]orderRefund退款返回结果：".json_encode($result));
            if($result['data']){
                if($result['data']['status']== 'OK'){

                }else{
                    $this->error('退款失败，请稍后重试：'.$result['data']['message']);
                }
            }else{
                $this->error('退款失败，请稍后重试');
            }
        }
        if(in_array($order['type'],[1,2])){
            Db::startTrans();
            $itemUpdateStatus= Db::name('wanlshop_order_item')->where(['id'=>$itemId])->update(['state'=>11]);
            $itemInfoUpdateStatus = Db::name('wanlshop_order_item_info')->where(['order_item_id'=>$itemId])->update(['spent'=>0]);
            if($itemUpdateStatus && $itemInfoUpdateStatus){
                $refund=[];
                $refund['user_id']=$order['user_id'];
                $refund['shop_id']=$order['shop_id'];
                $refund['order_id']=$order['id'];
                $refund['order_item_id']=$itemId;
                $refund['price']=$refundPrice;
                $refund['type']=1;
                $refund['refund_content']=$note;
                $refund['state']=4;
                $refund['createtime']=time();
                $refund['completetime']=time();

                Db::name('wanlshop_order_item_refund')->insert($refund);
                Db::commit();
                $this->success('订单退款成功！','',[]);
            }else{
                Db::rollback();
                $this->error('退款失败，请稍后重试：');
            }
        }elseif(in_array($order['type'],[4])){
            Db::startTrans();
            $refund=[];
            $refund['user_id']=$order['user_id'];
            $refund['shop_id']=$order['shop_id'];
            $refund['order_id']=$order['id'];
            $refund['order_item_id']=$itemId;
            $refund['price']=$refundPrice;
            $refund['type']=1;
            $refund['refund_content']=$note;
            $refund['state']=4;
            $refund['createtime']=time();
            $refund['completetime']=time();

            Db::name('wanlshop_order_item_refund')->insert($refund);
            $itemUpdateStatus= Db::name('wanlshop_order_item')->where(['id'=>$itemId])->update(['state'=>11,'spent'=>0]);
            if($itemUpdateStatus){
                Db::commit();
                $this->success('订单退款成功！','',[]);
            }else{
                Db::rollback();
                $this->error('退款失败，请稍后重试：');
            }
        }
        //$result=['data'=>['status'=>'OK','message'=>'333']];
        //print_r($result);exit;
    }

    public function orderGoodsRefund(){
        $param = $this->request->param();
        $conditions = [];
        $conditions['id'] = $param['order_id'];
        $pay_list = [];

        $order = Db::name('wanlshop_order')->field('data_type,coupon_id,user_id,shop_id,id,order_no')->where($conditions)->find();

        if (!empty($order)) {
            $conditions = [];
            $conditions['order_id'] = $param['order_id'];
            $conditions['pay_way_id'] = ['in',['9','10','12']];
            $pay_list = Db::name('wanlshop_pay_out_trade')->where($conditions)->select();
        }


        $refundPrice = 0;

        if(isset($param['goods'])){
            $goods = json_decode($param['goods'],true);
            foreach ($goods as $value){
                $refundPrice +=$value['order_goods_price'];
            }

            $req_params =[];
            $req_params['order_no'] =$order['order_no'];
            $req_params['refund_price'] =$refundPrice;

            $content = "";
            Db::startTrans();

            if (count($pay_list)) {
                foreach ($pay_list as $_key => $_value) {
                    if(in_array($_value['pay_way_id'],[10,12]) && $req_params['refund_price']>0){
                        $req_url = cdnurl('/api/Member/refundV2',true);//拉卡拉退款接口

                        write_log_record("[".date("Y-m-d H:i:s")."]退款接口参数33333：".json_encode($req_params));
                        $result = send_request($req_url, json_encode($req_params),'POST');
                        write_log_record("[".date("Y-m-d H:i:s")."]orderRefund退款返回结果：".json_encode($result));
                        if($result['data']){
                            if($result['data']['status']== 'OK'){

                            }else{
                                Db::rollback();
                                exception('退款失败，请稍后重试：'.$result['data']['message']);
                                // $this->error('退款失败，请稍后重试：'.$result['data']['message']);
                            }
                        }else{
                            Db::rollback();
                            exception('退款失败，请稍后重试');
                            // $this->error('退款失败，请稍后重试');
                        }
                    }

                    if($_value['pay_way_id']==9){
                        $userInfo = $this->user_model->find($order['user_id']);
                        $money_log_data = [];
                        $money_log_data['user_id'] = $userInfo['id'];
                        $money_log_data['money']= '-'.$order['user_id'];
                        $money_log_data['before']= sprintf("%.2f",$userInfo['money']);
                        $money_log_data['after']= sprintf("%.2f",$userInfo['money']) + sprintf("%.2f",$refundPrice);

                        $money_log_data['memo']= '用户退款订单编号:'.$order['order_no'];
                        $money_log_data['type']= 'pay';
                        $money_log_data['service_ids']= $order['id'];
                        $money_log_data['createtime']= time();
                        $res = $this->user_money_log_model->insert($money_log_data);
                        if(!$res || empty($res)){
                            write_log_record("退款失败1");
                            Db::rollback();
                            exception('退款失败');
                        }
                        $content .="\r\n退回用户余额：{$money_log_data['after']}元";
                        $res = $this->user_model->where('id',$userInfo['id'])->update(['money'=>$money_log_data['after']]);
                        if(!$res || empty($res)){
                            write_log_record("退款失败2");
                            Db::rollback();
                            exception('退款失败');
                        }
                    }
                }
            }

            //恢复优惠券
            if($order['coupon_id']){
                $content .="\r\n退回优惠券ID：{$order['coupon_id']}一张";
                Db::name('wanlshop_coupon_receive')->where(['id'=>$order['coupon_id']])->update(['state'=>1]);
            }
            if($order['data_type']=='goods'){
                $goods=Db::name('wanlshop_order_goods og')->where(['order_id'=>$order['id']])
                    ->join('wanlshop_goods g','og.goods_id=g.id')->field('g.id,g.views,g.sales,og.number')->select();
                foreach ($goods as $value){
                    $sales= $value['sales']-$value['number']>0 ?$value['sales']-$value['number']:0;
                    Db::name('wanlshop_goods')->where(['id'=>$value['id']])->update(['views'=>$value['views']+$value['number'],'sales'=>$sales]);
                }
            }else{
                $goods=Db::name('wanlshop_order_item')->where(['order_id'=>$order['id']])->select();
                foreach ($goods as $value){
                    Db::name('wanlshop_order_item')->where(['order_id'=>$order['id']])->update(['status'=>'hidden','spent'=>0,'gift'=>0]);
                    Db::name('wanlshop_order_item_info')->where(['order_item_id'=>$value['id']])->update(['spent'=>0,'status'=>'hidden']);
                }
            }
            $itemPay = Db::name('wanlshop_order_item_pay')->where(['order_id'=>$order['id']])->select();
            if($itemPay){
                foreach ($itemPay as $val){
                    if(in_array($val['card_type'],[1,2])){

                        $itemInfo = Db::name('wanlshop_order_item_info ii')->where(['ii.id'=>$val['order_item_info_id']])
                            ->join('wanlshop_order_item i','ii.order_item_id=i.id')->field("ii.*,i.name")->find();
                        Db::name('wanlshop_order_item_info')->where(['id'=>$val['order_item_info_id']])->setInc('spent',$val['total']);
                        Db::name('wanlshop_order_item')->where(['id'=>$itemInfo['order_item_id']])->setInc('spent',$val['total']);
                        $content .="\r\n退回次卡：{$itemInfo['name']}{$val['total']}次";
                    }elseif ($val['card_type']==4){
                        $itemInfo = Db::name('wanlshop_order_item')->where(['id'=>$val['order_item_info_id']])->find();
                        if($val['type']==1){
                            $content .="\r\n退回充值卡：{$itemInfo['name']}本金{$val['money']}元";
                            Db::name('wanlshop_order_item')->where(['id'=>$val['order_item_info_id']])->setInc('spent',$val['money']);
                        }else{
                            $content .="\r\n退回充值卡：{$itemInfo['name']}赠金{$val['money']}元";
                            Db::name('wanlshop_order_item')->where(['id'=>$val['order_item_info_id']])->setInc('gift',$val['money']);
                        }
                    }
                }
            }


            $itemUpdateStatus= Db::name('wanlshop_order')->where(['id'=>$param['order_id']])->update(['state'=>11]);
            if($itemUpdateStatus !==false){
                $refund=[];
                $refund['user_id']=$order['user_id'];
                $refund['shop_id']=$order['shop_id'];
                $refund['order_id']=$param['order_id'];
                $refund['price']=$refundPrice;
                $refund['type']=0;
                $refund['refund_content']=$param['note'];
                $refund['refund_detail']=$content;
                $refund['state']=4;
                $refund['createtime']=time();
                $refund['completetime']=time();


                Db::name('wanlshop_order_refund')->insert($refund);

                Db::commit();
                $this->success('订单退款成功！','',[]);
            }else{
                Db::rollback();
                $this->error('退款失败，请稍后重试：');
            }

        }
    }

    //充值卡续卡退款处理
    public function orderRechargeRefund(){
        $param = $this->request->param();

        $conditions = [];
        $conditions['id'] = $param['order_id'];
        $pay_list = [];

        $order = Db::name('wanlshop_order')->field('data_type,coupon_id,user_id,shop_id,id,order_no')->where($conditions)->find();

        if (!empty($order)) {
            $conditions = [];
            $conditions['order_id'] = $param['order_id'];
            $conditions['pay_way_id'] = ['in',['9','10','12']];
            $pay_list = Db::name('wanlshop_pay_out_trade')->where($conditions)->select();
        }

        $refundPrice = 0;

        if(isset($param['goods'])){
            $goods = json_decode($param['goods'],true);
            foreach ($goods as $value){
                $refundPrice +=$value['order_goods_price'];
            }

            $req_params =[];
            $req_params['order_no'] =$order['order_no'];
            $req_params['refund_price'] =$refundPrice;

            $content = "";
            Db::startTrans();

            if (count($pay_list)) {
                foreach ($pay_list as $_key => $_value) {
                    if(in_array($_value['pay_way_id'],[10,12]) && $req_params['refund_price']>0){
                        $req_url = cdnurl('/api/Member/refundV2',true);//拉卡拉退款接口

                        write_log_record("[".date("Y-m-d H:i:s")."]退款接口参数33333：".json_encode($req_params));
                        $result = send_request($req_url, json_encode($req_params),'POST');
                        write_log_record("[".date("Y-m-d H:i:s")."]orderRefund退款返回结果：".json_encode($result));
                        if($result['data']){
                            if($result['data']['status']== 'OK'){

                            }else{
                                Db::rollback();
                                exception('退款失败，请稍后重试：'.$result['data']['message']);
                                // $this->error('退款失败，请稍后重试：'.$result['data']['message']);
                            }
                        }else{
                            Db::rollback();
                            exception('退款失败，请稍后重试');
                            // $this->error('退款失败，请稍后重试');
                        }
                    }

                    if($_value['pay_way_id']==9){
                        $userInfo = $this->user_model->find($order['user_id']);
                        $money_log_data = [];
                        $money_log_data['user_id'] = $userInfo['id'];
                        $money_log_data['money']= '-'.$refundPrice;
                        $money_log_data['before']= sprintf("%.2f",$userInfo['money']);
                        $money_log_data['after']= sprintf("%.2f",$userInfo['money']) + sprintf("%.2f",$refundPrice);

                        $money_log_data['memo']= '用户退款订单编号:'.$order['order_no'];
                        $money_log_data['type']= 'pay';
                        $money_log_data['service_ids']= $order['id'];
                        $money_log_data['createtime']= time();
                        $res = $this->user_money_log_model->insert($money_log_data);
                        if(!$res || empty($res)){
                            write_log_record("退款失败1");
                            Db::rollback();
                            exception('退款失败');
                        }
                        $content .="\r\n退回用户余额：{$money_log_data['after']}元";
                        $res = $this->user_model->where('id',$userInfo['id'])->update(['money'=>$money_log_data['after']]);
                        if(!$res || empty($res)){
                            write_log_record("退款失败2");
                            Db::rollback();
                            exception('退款失败');
                        }
                    }
                }
            }

            //恢复优惠券
            if($order['coupon_id']){
                $content .="\r\n退回优惠券ID：{$order['coupon_id']}一张";
                Db::name('wanlshop_coupon_receive')->where(['id'=>$order['coupon_id']])->update(['state'=>1]);
            }

            //处理续卡数据
            if($order['data_type']=='cards'){
                //获取充值信息
                $order_items = Db::name('wanlshop_order_item_recharge')->where(['order_id' => $param['order_id']])->select();

                foreach ($order_items as $value){
                    //获取卡项信息
                    $order_item_info = Db::name('wanlshop_order_item')->where(['id' => $value['order_item_id']])->find();
                    $update_data = [];
                    $update_data['gift'] = $order_item_info['gift']-$value['gift']>0 ?$order_item_info['gift']-$value['gift']:0;
                    $update_data['spent'] = $order_item_info['spent']-$value['actual_price']>0 ?$order_item_info['spent']-$value['actual_price']:0;
                    $update_data['total'] = $order_item_info['total']-$value['actual_price']-$value['gift']>0 ?$order_item_info['total']-$value['actual_price']-$value['gift']:0;

                    Db::name('wanlshop_order_item')->where(['id'=>$param['order_item_id']])->update($update_data);
                    Db::name('wanlshop_order_item_recharge')->where(['id'=>$value['id']])->update(['state'=>4,'updatetime'=>time()]);
                }
            }

            //处理充值卡优惠
            $itemPay = Db::name('wanlshop_order_item_pay')->where(['order_id'=>$order['id']])->select();
            if($itemPay){
                foreach ($itemPay as $val){
                    if ($val['card_type']==4){
                        $itemInfo = Db::name('wanlshop_order_item')->where(['id'=>$val['order_item_info_id']])->find();
                        if($val['type']==1){
                            $content .="\r\n退回充值卡：{$itemInfo['name']}本金{$val['money']}元";
                            Db::name('wanlshop_order_item')->where(['id'=>$val['order_item_info_id']])->setInc('spent',$val['money']);
                        }else{
                            $content .="\r\n退回充值卡：{$itemInfo['name']}赠金{$val['money']}元";
                            Db::name('wanlshop_order_item')->where(['id'=>$val['order_item_info_id']])->setInc('gift',$val['money']);
                        }
                    }
                }
            }


            $itemUpdateStatus= Db::name('wanlshop_order')->where(['id'=>$param['order_id']])->update(['state'=>11]);
            if($itemUpdateStatus !==false){
                $refund=[];
                $refund['user_id']=$order['user_id'];
                $refund['shop_id']=$order['shop_id'];
                $refund['order_id']=$param['order_id'];
                $refund['price']=$refundPrice;
                $refund['type']=0;
                $refund['refund_content']=$param['note'];
                $refund['refund_detail']=$content;
                $refund['state']=4;
                $refund['createtime']=time();
                $refund['completetime']=time();


                Db::name('wanlshop_order_refund')->insert($refund);

                Db::commit();
                $this->success('订单退款成功！','',[]);
            }else{
                Db::rollback();
                $this->error('退款失败，请稍后重试：');
            }

        }
    }

    public function orderServiceRefund(){
        $refundPrice = $this->request->param('refund_price');
        $itemId = $this->request->param('order_item_id');
        $note = $this->request->param('note');

        $order = Db::name('wanlshop_order_goods g')
            ->join('wanlshop_order o', 'g.order_id = o.id', 'left')
            ->join('wanlshop_pay_out_trade t', 'o.id = t.order_id', 'left')
            ->field('o.actual_price,o.user_id,o.express_no,o.express_name,o.user_id,o.shop_id,o.id,g.number,g.goods_id,o.order_no,t.pay_way_id')
            ->where(['o.id'=>$itemId])
            ->find();

        $req_params =[];
        $req_params['order_no'] =$order['order_no'];
        $req_params['refund_price'] =$order['actual_price'];


        Db::startTrans();
        if(in_array($order['pay_way_id'],[10,12]) && $req_params['refund_price']>0){
            $req_url = cdnurl('/api/Member/refundV2',true);//拉卡拉退款接口

            write_log_record("[".date("Y-m-d H:i:s")."]退款接口参数33333：".json_encode($req_params));
            $result = send_request($req_url, json_encode($req_params),'POST');
            write_log_record("[".date("Y-m-d H:i:s")."]orderRefund退款返回结果：".json_encode($result));
            if($result['data']){
                if($result['data']['status']== 'OK'){

                }else{
                    $this->error('退款失败，请稍后重试：'.$result['data']['message']);
                }
            }else{
                $this->error('退款失败，请稍后重试');
            }
        }elseif($order['pay_way_id']==9){
            $userInfo = $this->user_model->find($order['user_id']);
            $money_log_data = [];
            $money_log_data['user_id'] = $userInfo['id'];
            $money_log_data['money']= '-'.$order['user_id'];
            $money_log_data['before']= sprintf("%.2f",$userInfo['money']);
            $money_log_data['after']= sprintf("%.2f",$userInfo['money']) + sprintf("%.2f",$order['actual_price']);

            $money_log_data['memo']= '用户退款订单编号:'.$order['order_no'];
            $money_log_data['type']= 'pay';
            $money_log_data['service_ids']= $order['id'];
            $money_log_data['createtime']= time();
            $res = $this->user_money_log_model->insert($money_log_data);
            if(!$res || empty($res)){
                write_log_record("订单添加失败2");
                Db::rollback();
                exception('订单添加失败');
            }
            $res = $this->user_model->where('id',$userInfo['id'])->update(['money'=>$money_log_data['after']]);
            if(!$res || empty($res)){
                write_log_record("订单添加失败3");
                Db::rollback();
                $this->error('退款失败，请稍后重试：');
            }
        }

        $itemPay = Db::name('wanlshop_order_item_pay')->where(['order_id'=>$order['id']])->select();
        if($itemPay){
            foreach ($itemPay as $val){
                if(in_array($val['card_type'],[1,2])){

                    $itemInfo = Db::name('wanlshop_order_item_info')->where(['id'=>$val['order_item_info_id']])->find();
                    Db::name('wanlshop_order_item_info')->where(['id'=>$val['order_item_info_id']])->setInc('spent',$val['total']);
                    Db::name('wanlshop_order_item')->where(['id'=>$itemInfo['order_item_id']])->setInc('spent',$val['total']);
                }elseif ($val['card_type']==4){
                    if($val['type']=1){
                        Db::name('wanlshop_order_item')->where(['id'=>$val['order_item_info_id']])->setInc('spent',$val['money']);
                    }else{
                        Db::name('wanlshop_order_item')->where(['id'=>$val['order_item_info_id']])->setInc('gift',$val['money']);
                    }
                }
            }
        }


        $itemUpdateStatus= Db::name('wanlshop_order_goods')->where(['id'=>$itemId])->update(['state'=>11]);
        if($itemUpdateStatus !==false){
            $refund=[];
            $refund['user_id']=$order['user_id'];
            $refund['shop_id']=$order['shop_id'];
            $refund['order_id']=$order['id'];
            $refund['price']=$order['actual_price'];
            $refund['type']=0;
            $refund['refund_content']=$note;
            $refund['state']=4;
            $refund['createtime']=time();
            $refund['completetime']=time();

            Db::name('wanlshop_order_service_refund')->insert($refund);
            $goods=Db::name('wanlshop_goods')->where(['id'=>$order['goods_id']])->find();
            $sales= $goods['sales']-$order['number']>0 ?$goods['sales']-$order['number']:0;
            Db::name('wanlshop_goods')->where(['id'=>$order['goods_id']])->update(['views'=>$goods['views']+$order['number'],'sales'=>$sales]);
            Db::commit();
            $this->success('订单退款成功！','',[]);
        }else{
            Db::rollback();
            $this->error('退款失败，请稍后重试：');
        }
        //$result=['data'=>['status'=>'OK','message'=>'333']];
        //print_r($result);exit;
    }

    public function index(){
        // if ($this->shop_id != 1) {
        //     $this->redirect('/cashdesk/Index/notice.html');
        // }
        
        $limit = 18;
        $page = 1;
        
        if (true === $this->request->isAjax()) {
            $page = $this->request->param('page',1);
            $userid = $this->request->param('userid',0);
            $cateid = $this->request->param('cateid',0);
            $searchword = trim($this->request->param('searchword',''));
            $type = $this->request->param('type','goods');//goods/services/cards
            $list = [];
            $data = ['category'=>[],'list'];
            if (in_array($type,['goods','services'])) {
                $pid = $type == 'goods'?$this->goods_pid:$this->service_pid;
                $where = [];
                $where['pid'] = $pid;
                $where['status'] = 'normal';
                $where['publishing_platform'] = ['in',['0','2']];
                $category = $this->goods_category_model->field('id,name')->where($where)->select();
                $cateid = count($category)>0 && $cateid==0?$category[0]['id']:$cateid;
                $condition = [];
                $condition['shop_id'] = $this->shop_id;
                $condition['category_id'] = $cateid;
                $condition['status'] = 'normal';
                $condition['grounding'] = '1';
                $condition['gdtype'] = $type == 'goods'?'0':'1';
                $condition['publishing_platform'] = ['in',['0','2']];
                if (!empty($searchword)) {
                    $condition['title'] = ['like','%'.$searchword.'%'];
                }

                $list = $this->goods_model
                    ->field('id,image,title,price,vip_price')
                    ->where($condition)
                    ->order('id desc')
                    ->paginate($limit, false, ['page' => $page])
                    ->each(function ($v) {
                        $v['image'] = get_img($v['image']);
                        return $v;
                    })->toArray();
                $data = [
                    'category' => $category,
                    'list'     => $list
                ];
            }elseif ($type == 'cards') {
                $limit = 6;
                $shop_id = $this->shop_id;
                $pid = $cateid == 0?$this->card_pid:$cateid;
                if($pid != 6){
                    $where = ['type'=>$pid,'shop_id'=>$shop_id,'price'=>['>',0],'activity_type'=>'goods','status'=>'normal'];
                
                    if (!empty($searchword)) {
                        $where['name'] = ['like','%'.$searchword.'%'];
                    }
                    $list = $this->card_category_model
                        ->where($where)
                        ->where(function ($query) use ($shop_id) {
                            $query->where('stock', '0')
                                ->whereOr(function ($query) use ($shop_id) {
                                    $query->where('stock', '2')
                                        ->whereRaw("FIND_IN_SET($shop_id, shop_ids)");
                                });
                        })
                        ->order('createtime', 'desc')
                        ->paginate($limit, false, ['page' => $page])->each(function (&$v) {
                            if (!isset($v['card_service'])) {
                                $v['card_service'] = '';
                            }
                            if (!isset($v['time'])) {
                                $v['time'] = '';
                            }
                            if (!isset($v['type_name'])) {
                                $v['type_name'] = '';
                            }

                            $v['type_name'] = $this->card_type_name_arr[$v['type']-1];

                            if ($v['validity'] == 0) {
                                $v['time'] = '永久有效';
                            }elseif ($v['validity'] == 1) {
                                $v['time'] = date('Y-m-d', $v['validitytime']);
                            }elseif ($v['validity'] == 2) {
                                $v['time'] = '购买后' . $v['validitydays'] . '天内有效';
                            }elseif ($v['validity'] == 3) {
                                $v['time'] = '首次使用后' . $v['validitydays'] . '天内有效';
                            }

                            $ser = Db::name('item_info i')->where('i.item_id', $v['id'])
                                // ->join('wanlshop_goods_sku s', 'i.sku_id = s.id', 'left')->select();
                                ->join('wanlshop_goods s', 'i.goods_id = s.id', 'left')->select();
                            foreach ($ser as $kk => $vv) {
                                $v['card_service'] .= $vv['title'] . '、';
                            }
                            return $v;
                        })->toArray();

                    foreach ($list['data'] as $key => &$value) {
                        $value['cateid'] = $value['type'];
                        $value['unit_price'] = 0;
                        if ($value['type'] != 4 && $value['total'] != 0) {
                            $value['unit_price'] = floatval($value['price']/$value['total']);
                        }

                        //卡项失效
                        if ($value['validity'] == 1 && $value['validitytime'] < time()) {
                            unset($list['data'][$key]);
                        }
                    }
                    $data = [
                        'category' => $this->card_type_arr,
                        'list'     => $list
                    ];
                }else{
                    $where = ['type'=>4,'user_id'=>$userid,'activity_type'=>'goods','status'=>'normal'];
                
                    if (!empty($searchword)) {
                        $where['name'] = ['like','%'.$searchword.'%'];
                    }
                    $list = $this->order_item_model
                        ->where($where)
                        ->order('createtime', 'desc')
                        ->paginate($limit, false, ['page' => $page])->each(function (&$v) {
                            if (!isset($v['time'])) {
                                $v['time'] = '';
                            }
                            if (!isset($v['type_name'])) {
                                $v['type_name'] = '';
                            }

                            $v['type_name'] = $this->card_type_name_arr[$v['type']-1];

                            if ($v['validity'] == 0) {
                                $v['time'] = '永久有效';
                            }elseif ($v['validity'] == 1) {
                                $v['time'] = date('Y-m-d', $v['validitytime']);
                            }elseif ($v['validity'] == 2) {
                                $v['time'] = '购买后' . $v['validitydays'] . '天内有效';
                            }elseif ($v['validity'] == 3) {
                                $v['time'] = '首次使用后' . $v['validitydays'] . '天内有效';
                            }
                            return $v;
                        })->toArray();
                        // print_r($this->order_item_model->getLastSql());die;
                    foreach ($list['data'] as $key => &$value) {
                        $value['unit_price'] = 0;
                        $value['vip_price'] = 0;
                        $value['cateid'] = 6;
                        $value['price'] = (float)sprintf("%.2f", $value['gift'] + $value['spent']);

                        //卡项失效
                        if ($value['validity'] == 1 && $value['validitytime'] < time()) {
                            unset($list['data'][$key]);
                        }
                    }
                    $data = [
                        'category' => $this->card_type_arr,
                        'list'     => $list
                    ];
                }  
            }
            return $this->success('', '', $data);
        }
        return $this->view->fetch();
    }

    //添加会员--已完成
    public function adduser(){
        $mobile = $this->request->param('mobile');
        $nickname = $this->request->param('nickname','');
        $gender = $this->request->param('gender');

        if (!preg_match('/^1[3-9]\d{9}$/', $mobile)){
            return  $this->error('手机号码格式错误！');
        }
        $user =  $this->user_model->where('mobile|username',$mobile)->find();

        if ($user){
            return  $this->error('该会员已存在');
        }
       Db::startTrans();
        try {
            $ip = request()->ip();
            $time = time();
            $data= [
                'shop_id'   => $this->shop_id,
                'username'  => $mobile,
                'nickname'  => empty($nickname) ? substr_replace($mobile, '****', 3, 4) : $nickname,
                'salt'      => Random::alnum(),
                'jointime'  => $time,
                'avatar'    =>'/assets/cashdesk/img/default_avator.png',
                'gender'    => $gender,
                'joinip'    => $ip,
                'logintime' => $time,
                'mobile'    => $mobile,
                'loginip'   => $ip,
                'prevtime'  => $time,
                'status'    => 'normal'
            ];
            $password = 123456;
            $data['password'] = $this->getEncryptPassword($password, $data['salt']);
            $this->user_model->save($data);
            Db::commit();
        }catch (Exception $exception){
            Db::rollback();
            return  $this->error('失败');
        }
        return  $this->success('添加成功');
    }

    //选择会员--已完成
    public function searchuser(){

        $mobile = $this->request->param('mobile');
        // if (!preg_match('/^1[3-9]\d{9}$/', $mobile)){
        //     return  $this->error('手机号码错误');
        // }

        $where = [];
        $where['mobile|username|nickname'] = ['like','%'.$mobile.'%'];
        $where['user.status'] = 'normal';

        $list =  $this->user_model
                ->field('id,username,nickname,mobile,money,score,group_id,avatar')
                ->with(['group', 'shop'])
                ->where($where)
                ->select();
        if (count($list) == 0){
            return  $this->error('没有符合条件的会员');
        }
        return  $this->success('','',$list);
    }

    //选择服务人员--已完成
    public function getstafflist(){
        $list = [];
        if (true === $this->request->isAjax()) {
            $list = $this->staff_model->alias('s')
                ->field('s.id,s.name,s.portraitimage,r.name as rank_name')
                ->where(['s.shop_id'=>$this->shop_id,'s.status'=>1])
                ->join('staff_rank r','r.id = s.rank')->select();
        }
        return $this->success('', '', $list);
    }

    //获取用户优惠券--已完成
    public function getcoupons(){
        $data = $this->request->param();
        if (!isset($data['userid'])){
            return  $this->error('用户不存在');
        }
        $user_id = $data['userid'];
        $user =  $this->user_model->where(['id'=>$user_id,'status'=>'normal'])->find();
        if (!$user){
            return  $this->error('当前会员不存在');
        }

        //获取用户优惠券
        $condition = ['user_id'=>$user_id,'shop_id'=>$this->shop_id,'type'=>'reduction','state'=>1,'enddate'=>['>=',date("Y-m-d")]];
        $coupon = $this->user_coupon_model->where($condition)->select();
        return  $this->success('','',$coupon);
    }

    //获取支付方式
    public function getpayways(){
        $pay_list = [];
        $list = $this->pay_model->where('status','normal')->select();
        // 初始化结果数组
        $result = [];

        // 遍历原数组
        foreach ($list as $item) {
            $type = $item['type'];
            // 如果结果数组中不存在该type的分组，则初始化
            if (!isset($result[$type])) {
                $type_name = '现金(记账)';
                $type_index = 2;
                $type_img = '/assets/cashdesk/img/payment_cash_icon.svg';
                if ($type == 1) {
                    $type_index = 3;
                    $type_name = '余额支付';
                    $type_img = '/assets/cashdesk/img/payment_balance_icon.svg';
                }elseif ($type == 2) {
                    $type_name = '景珍支付';
                    $type_index = 1;
                    $type_img = '/assets/cashdesk/img/payment_lakala_icon.svg';
                }
                $result[$type] = [
                    'name' => $type_name,
                    'index' => $type_index,
                    'img' => $type_img,
                    'sublist' => []
                ];
            }
            // 将当前项添加到对应type的sublist中
            $result[$type]['sublist'][] = $item;
        }

        // 重置数组索引
        usort($result, function ($a, $b) {
            return $a['index'] - $b['index']; 
            // 返回负数，$a 排在 $b 前；返回正数，$b 排在 $a 前；返回 0，顺序不变
        });

        $result = array_values($result);
        return  $this->success('','',$result);
    }

    //跳转到支付订单页面
    public function order(){
        return $this->view->fetch();
    }

    //获取客户已购买的权益卡
    public function getusercards(){
        $data = $this->request->param();
        if (!isset($data['userid'])){
            return  $this->error('用户不存在');
        }
        if (!isset($data['specid'])){
            return  $this->error('当前商品不存在');
        }
        
        $user_id = $data['userid'];
        $spec_id = $data['specid'];
        $user =  $this->user_model->where(['id'=>$user_id,'status'=>'normal'])->find();
        if (!$user){
            return  $this->error('当前会员不存在');
        }

        //获取可用的卡项,通过sku_id获取goods_id,进而获取当前商品铺设的店铺里面的商品
        $goods_id = $this->goods_sku_model->where(['id'=>$spec_id])->value('goods_id');

        $goods_ids = [];
        if ($this->shop_id == 1) {
            $_goods_id = $goods_id;
        }else{
            $_goods_id = $this->goods_shop_model->where(['new_goods_id'=>$goods_id])->value('goods_id');
        }

        $goods_ids = $this->goods_shop_model->where(['goods_id'=>$_goods_id])->column('new_goods_id');

        $goods_ids = array_filter(array_unique(array_merge([$goods_id],$goods_ids,[$_goods_id])));

        $conditions['goods_id'] = ['in',$goods_ids];
        $conditions['status'] = 'normal';

        $order_item_ids = $this->order_item_info_model->where($conditions)->column('order_item_id');

        if (count($order_item_ids) == 0) {
            return  $this->error('没有可用的卡项');
        }

        $conditions = [];
        $conditions['user_id'] = $user_id;
        $conditions['i.type'] = ['in',[1,2,3]];
        $conditions['i.status'] = 'normal';
        $conditions['activity_type'] = 'goods';
        $conditions['i.id'] = ['in',$order_item_ids];
        $conditions['in.spent'] = ['>',0];
        $conditions['in.goods_id'] = ['in',$goods_ids];

        $list = $this->order_item_model->alias('i')
            ->where($conditions)
            ->field('i.id as card_id,in.id,in.spent,i.name,i.gift,i.validity,in.total,i.validitytime,i.price,i.total as total_number,i.type,in.goods_id,in.sku_id,i.stock,i.item_id,i.order_id,shop_ids')
            ->join('wanlshop_order_item_info in', 'i.id = in.order_item_id', 'left')
            ->order('i.createtime', 'desc')
            ->select();

        foreach ($list as $k => &$v){
            $v['unit_price'] = floatval($v['price']/$v['total_number']);
            //判断卡项有效期
            if ($v['validity'] == 1 && $v['validitytime'] < time()) {
                unset($list[$k]);
            }

            //判断卡项门店是否符合 0=全部门店,1=指定门店,2=仅售卡门店可用
            if ($v['stock'] == 1) {//指定门店
                $shop_ids = explode(',', $v['shop_ids']);
                if (!in_array($this->shop_id,$shop_ids)) {
                    unset($list[$k]);
                }
            }elseif($v['stock'] == 2 && $v['shop_id'] != $this->shop_id){
                unset($list[$k]);
            }

            $v['is_buy'] = 1;
            if (!isset($v['card_service'])) {
                $v['card_service'] = '';
            }
            if ($v['validitytime'] == 9999){
                $v['time'] = '永久有效';
            }else{
                $v['time'] = date('Y-m-d', $v['validitytime']).'前有效';
            }
            $v['checknum'] = 0;
            if (!isset($v['type_name'])) {
                $v['type_name'] = '';
            }

            $v['type_name'] = $this->card_type_name_arr[$v['type']-1];

            $goods_name = $this->goods_model->where('id',$v['goods_id'])->value('title');
            $v['card_service'] = '<'.$goods_name.'-剩余次数：'.$v['spent'].'/'.$v['total'].'> ';

            // $where = [];
            // $where['i.item_id'] = $v['item_id'];
            // $where['i.order_id'] = $v['order_id'];
            // $where['i.sku_id'] = $spec_id;
            // $res = $this->order_item_info_model->alias('i')
            //     ->where($where)
            //     ->join('wanlshop_goods_sku s', 'i.sku_id = s.id', 'left')
            //     ->join('wanlshop_goods g', 'g.id = s.goods_id', 'left')
            //     ->select();
            // foreach ($res as $k2 => $v2) {
            //     $v['card_service'] .= '<'.$v2['sku_id'].'-'.$v2['title'].'-'.$v2['difference'] . '> ';
            //     // $v['spent'] = $v['spent'] > $v2['spent']?$v2['spent']:$v['spent'];
            // }
        }
        unset($v);
        return  $this->success('','',$list);
    }

    public function getmyordercards(){
        $data = $this->request->param();
        if (!isset($data['userid'])){
            return  $this->error('用户不存在');
        }

        $user_id = $data['userid'];
        $user =  $this->user_model->where(['id'=>$user_id,'status'=>'normal'])->find();
        if (!$user){
            return  $this->error('当前会员不存在');
        }

        
        $where = ['user_id' => $user_id, 'activity_type'=>'goods','status' => 'normal','spent'=>['>',0],'type'=>['<>','4']];
        $list1 = $this->order_item_model->where($where)->order('createtime', 'desc')->select();
        $where = ['user_id' => $user_id, 'activity_type'=>'goods','type'=>'4'];
        $list2 = $this->order_item_model->where($where)->order('createtime', 'desc')->select();
        $list = array_merge($list2,$list1);
        foreach ($list as $k => &$v){
            $v['unit_price'] = 0;
            if ($v['type'] != 4) {
                $v['unit_price'] = floatval($v['price']/$v['total']);
            }
            
            //判断卡项有效期
            if ($v['validity'] == 1 && $v['validitytime'] < time()) {
                unset($list[$k]);
            }

            //判断卡项门店是否符合 0=全部门店,1=指定门店,2=仅售卡门店可用
            if ($v['stock'] == 1) {//指定门店
                $shop_ids = explode(',', $v['shop_ids']);
                if (!in_array($this->shop_id,$shop_ids)) {
                    unset($list[$k]);
                }
            }elseif($v['stock'] == 2 && $v['shop_id'] != $this->shop_id){
                unset($list[$k]);
            }

            $v['is_buy'] = 1;
            if (!isset($v['card_service'])) {
                $v['card_service'] = '';
            }
            if ($v['validitytime'] == 9999){
                $v['time'] = '永久有效';
            }else{
                $v['time'] = date('Y-m-d', $v['validitytime']).'前有效';
            }
            $v['checknum'] = 0;
            if (!isset($v['type_name'])) {
                $v['type_name'] = '';
            }

            $v['type_name'] = $this->card_type_name_arr[$v['type']-1];

            // $goods_name = $this->goods_model->where('id',$v['goods_id'])->value('title');
            // $v['card_service'] = '<'.$goods_name.'-剩余次数：'.$v['spent'].'/'.$v['total'].'> ';


            $res = $this->order_item_info_model->alias('i')->where('i.item_id', $v['item_id'])->where('i.order_id', $v['order_id'])
                ->join('wanlshop_goods_sku s', 'i.sku_id = s.id', 'left')
                ->join('wanlshop_goods g', 'g.id = s.goods_id', 'left')
                ->select();
            foreach ($res as $k2 => $v2) {
                $v['card_service'] .= '<'.$v2['title']. ' 剩余次数:'.$v2['spent'].'/'.$v2['total'].'> ';
            }
        }
        unset($v);
        return  $this->success('','',$list);
    }

    //获取客户已购买的权益卡
    public function getuserordercards(){
        $data = $this->request->param();
        if (!isset($data['userid'])){
            return  $this->error('用户不存在');
        }
        
        $user_id = $data['userid'];
        $user =  $this->user_model->where(['id'=>$user_id,'status'=>'normal'])->find();
        if (!$user){
            return  $this->error('当前会员不存在');
        }

        $where = ['user_id' => $user_id, 'type'=>'4','activity_type'=>'goods','status' => 'normal','gift|spent' => ['>',0]];
        $list = $this->order_item_model->where($where)->select();

        foreach ($list as $k => &$v){
            //判断卡项有效期
            if ($v['validity'] == 1 && $v['validitytime'] < time()) {
                unset($list[$k]);
            }

            //判断卡项门店是否符合 0=全部门店,1=指定门店,2=仅售卡门店可用
            if ($v['stock'] == 1) {//指定门店
                $shop_ids = explode(',', $v['shop_ids']);
                if (!in_array($this->shop_id,$shop_ids)) {
                    unset($list[$k]);
                }
            }elseif($v['stock'] == 2 && $v['shop_id'] != $this->shop_id){
                unset($list[$k]);
            }

            $v['is_buy'] = 1;
            if ($v['validitytime'] == 9999){
                $v['time'] = '永久有效';
            }else{
                $v['time'] = date('Y-m-d', $v['validitytime']).'前有效';
            }
            $v['checknum'] = 0;
            if (!isset($v['type_name'])) {
                $v['type_name'] = '';
            }

            $v['type_name'] = $this->card_type_name_arr[$v['type']-1];
        }
        unset($v);
        return  $this->success('','',$list);
    }

    //用户密码加密--已完成
    public function getEncryptPassword($password, $salt = ''){
        return md5(md5($password) . $salt);
    }

    // 生成二维码--已完成
    public function build(){
        $config = get_addon_config('qrcode');
        if (isset($config['limitreferer']) && $config['limitreferer']) {
            $referer = $this->request->server('HTTP_REFERER', '');
            $refererInfo = parse_url($referer);
            $refererHost = $referer && $refererInfo ? $refererInfo['host'] : '';
            $refererHostArr = explode('.', $refererHost);
            $wildcardDomain = '';
            if (count($refererHostArr) > 2) {
                $refererHostArr[0] = '*';
                $wildcardDomain = implode('.', $refererHostArr);
            }
            $allowRefererList = $config['allowrefererlist'] ?? '';
            $domainArr = explode("\n", str_replace("\r", "", $allowRefererList));
            $domainArr = array_filter(array_unique($domainArr));
            $domainArr[] = request()->host(true);
            $inAllowList = false;

            if (in_array('*', $domainArr) || ($refererHost && in_array($refererHost, $domainArr)) || ($wildcardDomain && in_array($wildcardDomain, $domainArr))) {
                $inAllowList = true;
            }

            if (!$inAllowList && (!$referer && $config['allowemptyreferer'])) {
                $inAllowList = true;
            }

            if (!$inAllowList) {
                $response = Response::create('暂无权限', 'html', 403);
                throw new HttpResponseException($response);
            }
        }
        $params = $this->request->get();
        $params = array_intersect_key($params, array_flip(['text', 'size', 'padding', 'errorlevel', 'foreground', 'background', 'logo', 'logosize', 'logopath', 'label', 'labelfontsize', 'labelalignment']));

        $params['text'] = $this->request->get('text', $config['text'], 'trim');
        $params['label'] = $this->request->get('label', $config['label'], 'trim');

        $qrCode = \addons\qrcode\library\Service::qrcode($params);

        $mimetype = $config['format'] == 'png' ? 'image/png' : 'image/svg+xml';

        $response = Response::create()->header("Content-Type", $mimetype);

        // 直接显示二维码
        header('Content-Type: ' . $qrCode->getContentType());
        $response->content($qrCode->writeString());

        // 写入到文件
        if ($config['writefile']) {
            $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/';
            if (!is_dir($qrcodePath)) {
                @mkdir($qrcodePath);
            }
            if (is_really_writable($qrcodePath)) {
                $filePath = $qrcodePath . md5(implode('', $params)) . '.' . $config['format'];
                $qrCode->writeFile($filePath);
            }
        }

        return $response;
    }

    /**
     *  :param principal: 本金初始金额
        :param bonus: 赠金初始金额
        :param amount: 扣款金额
        :param deduct_order: 扣款顺序，1为先扣本金再扣赠金，2为先扣赠金再扣本金
        :return: 剩余本金、剩余赠金、扣除的本金金额、扣除的赠金
     * */
    public function deductOrder($principal, $bonus, $amount, $deduct_order=1){
        $deducted_principal = 0;//扣除的本金金额
        $deducted_bonus = 0;//扣除的赠金
        $remaining_principal = $principal;//剩余本金
        $remaining_bonus = $bonus;//剩余赠金

        if ($deduct_order == 1) {//先扣本金再扣赠金
            if ($amount <= $remaining_principal) {
                $deducted_principal = $amount;
                $remaining_principal -= $amount;
            }else{
                // 本金扣完，再扣赠金
                $deducted_principal = $remaining_principal;
                $remaining_principal = 0;
                $deducted_bonus = $amount - $deducted_principal;

                if ($deducted_bonus <= $remaining_bonus) {
                    $remaining_bonus -= $deducted_bonus;
                }else{
                    $deducted_bonus = $remaining_bonus;
                    $remaining_bonus = 0;
                }
            }
        }elseif ($deduct_order == 2) {//先扣赠金再扣本金
            if ($amount <= $remaining_bonus){
                $deducted_bonus = $amount;
                $remaining_bonus -= $amount;
            }else{
                $deducted_bonus = $remaining_bonus;
                $remaining_bonus = 0;
                $deducted_principal = $amount - $deducted_bonus;

                if($deducted_principal <= $remaining_principal){
                    $remaining_principal -= $deducted_principal;
                }else{
                    $deducted_principal = $remaining_principal;
                    $remaining_principal = 0;
                }
            }
        }

        return [
            'deducted_principal'=>$deducted_principal,
            'deducted_bonus'=>$deducted_bonus,
            'remaining_principal'=>$remaining_principal,
            'remaining_bonus'=>$remaining_bonus,
        ];
    }

     //获取会员优惠折扣
    public function getleveldiscount(){
        $res = [];
        $list = $this->user_group_model->where(['status'=>'normal'])->select();
        if (count($list)>0) {
            foreach ($list as $key => $value) {
                $res[$value['id']] = (float)sprintf("%.2f", $value['discount']/100);
            }
        }
        return json(['code'=>1,'msg'=>'success','data'=>$res]);
    }
    //创建订单
    public function createorder(){
        // $uid = 1;
        $data = $this->request->param();
        write_log_record("订单参数：".json_encode($data));
        //订单类型
        $datatype = $data['datatype'];
        //订单金额统计
        $orderCount = $data['ordercount'];
        //订单详细信息
        $orderInfo = $data['orderinfo'];
        //支付信息
        $payInfo = $data['payinfo'];
        //客户信息
        $userInfo = $data['userinfo'];
        //销售人员
        $staff_id = isset($orderCount['serveid'])?$orderCount['serveid']:0;
        //小白盒扫码数据
        $scanresult = isset($data['scanresult'])?$data['scanresult']:'';
        //拉卡拉二维码支付数据
        $lal_qrcode = [];
        //拉卡拉扫码支付数据
        $lal_scan = [];

        // 创建数据
        $push=[];
        $shopPo = array_column(Db::name('wanlshop_shop')->where(['status'=>'normal'])->field(['id','shopname'])->select(),'shopname','id');
        $shop_info = $this->shop_model->where('id', $this->shop_id)->find();
        if(!$shop_info || empty($shop_info)){
            return $this->error('店铺不存在！');
        }

        $cur_pay_type = '';
        $cur_pay_amount = 0;

        Db::startTrans();
        try{
            
            $userInfo = $this->user_model->find($userInfo['id']);
            //购买成功通知
            $push['shop_card_times_success'][0]=[
                'order_price'=>$orderCount['totalfee'],
                'time'=>date('Y-m-d H:i:s',time()),
                'open_id'=>$userInfo['wechat_openid'],
            ];
            if(!$userInfo || empty($userInfo)){
                Db::rollback();
                exception('用户不存在！');
            }
            $actual_price = sprintf("%.2f",($orderCount['totalfee'] - $orderCount['discountfee'] - $orderCount['carddiscount'] - $orderCount['discount']));

            $actual_price = $actual_price < 0?0:$actual_price;

            //卡项优惠
            $order_price = sprintf("%.2f",$orderCount['totalfee'] - $orderCount['discountfee'] - $orderCount['discount']);
            
            //判断支付数据
            if(!$payInfo || count($payInfo) == 0){
                Db::rollback();
                exception('请选择支付方式');
            }

            $coupon_id = isset($orderInfo['coupon']['coupon_id'])?$orderInfo['coupon']['coupon_id']:0;

            //订单主表数据
            $order_no = create_order_sn($userInfo['id']);
            $order_data = [
                'data_type'         =>  $data['datatype']=='cards'?'cards':'goods',
                'user_id'           =>  $userInfo['id'],
                'shop_id'           =>  $this->shop_id,
                'order_no'          =>  $order_no,
                'state'             =>  '6',
                'coupon_id'         =>  $coupon_id,
                'createtime'        =>  time(),
                'price'             =>  $orderCount['originalfee'],
                'save_prcie'        =>  $orderCount['totalfee'],
                'actual_price'      =>  $actual_price,
                'paymenttime'       =>  time(),
                'dealtime'          =>  time(),
                'ontype'            =>  '2',
                'staff_ids'         =>  $staff_id,
                'remarks'           =>  $orderCount['remarks'],
                'discountfee'       =>  $orderCount['discountfee'],
                'upricefee'         =>  $orderCount['upricefee'],
                'carddiscount'      =>  $orderCount['carddiscount'],
                'discount'          =>  $orderCount['discount'],
            ];

            if($orderCount['issupplement'] == 1){
                $order_data['issupplement'] = 1;
                $order_data['dealtime'] = $order_data['createtime'] = strtotime($orderCount['supplementtime']);
            }

            foreach ($payInfo as $pkey => $pvalue) {
                //余额支付
                if($pvalue['id'] == 9 && $userInfo['money'] < $pvalue['amount']){
                    Db::rollback();
                    exception('用户余额不足！');
                }

                if($pvalue['id'] == 12 && empty($scanresult)){
                    Db::rollback();
                    exception('未获取到扫码数据');
                }

                if(in_array($pvalue['id'],[10,12])){
                    if($pvalue['id'] == 10){
                        $lal_qrcode = $pvalue;
                        $cur_pay_type = 'qrcode';
                        $cur_pay_amount = $lal_qrcode['amount'];
                    }else{
                        $lal_scan = $pvalue;
                        $cur_pay_type = 'scan';
                        $cur_pay_amount = $pvalue['amount'];
                    }

                    $order_data['state'] = 1;
                    unset($order_data['paymenttime']);
                    unset($order_data['dealtime']);
                }
            }

            $order_id = $this->order_model->insertGetId($order_data);

            if(!$order_id || empty($order_id)){
                write_log_record("订单添加失败1");
                Db::rollback();
                exception('订单添加失败');
            }

            //处理用户余额
            foreach ($payInfo as $pkey1 => $pvalue1) {
                if($pvalue1['id'] == 9){
                    $money_log_data = [];
                    $money_log_data['user_id'] = $userInfo['id'];
                    $money_log_data['money']= '-'.$pvalue1['amount'];
                    $money_log_data['before']= sprintf("%.2f",$userInfo['money']);
                    $money_log_data['after']= sprintf("%.2f",$userInfo['money']) - sprintf("%.2f",$pvalue1['amount']);

                    $money_log_data['memo']= '用户购买商品付款，订单编号:'.$order_no;
                    $money_log_data['type']= 'pay';
                    $money_log_data['service_ids']= $order_id;
                    $money_log_data['createtime']= time();
                    $res = $this->user_money_log_model->insert($money_log_data);
                    if(!$res || empty($res)){
                        write_log_record("订单添加失败2");
                        Db::rollback();
                        exception('订单添加失败');
                    }
                    $_res = $this->user_model->where('id',$userInfo['id'])->update(['money'=>$money_log_data['after']]);
                    if(!$res || empty($res)){
                        write_log_record("订单添加失败3");
                        Db::rollback();
                        exception('订单添加失败');
                    }
                }
            }

            //处理优惠券数据
            if(isset($orderCount['coupon']) && count($orderCount['coupon']) > 0 && $orderCount['discount']>0){
                $condition = [];
                $condition['id'] = $orderCount['coupon']['coupon_id'];
                $condition['state'] = 1;

                $coupon_info = $this->user_coupon_model->where($condition)->find();
                if(!$coupon_info || empty($coupon_info)){
                    write_log_record("订单添加失败4");
                    Db::rollback();
                    exception('订单添加失败');
                }

                $up_data = ['order_id'=>$order_id,'state'=>2];
                $res = $this->user_coupon_model->where($condition)->update($up_data);

                if(!$res || empty($res)){
                    write_log_record("订单添加失败5");
                    Db::rollback();
                    exception('订单添加失败');
                }
            }

            $order_deducted_fee = 0;
            //处理充值卡数据
            if(isset($orderCount['cardcoupon']) && count($orderCount['cardcoupon']) > 0 && $orderCount['carddiscount']>0){
                //卡项详情
                $card_id = $orderCount['cardcoupon']['card_id'];
                $card_price = $orderCount['cardcoupon']['card_price'];

                $order_item = $this->order_item_model->where(['id'=>$card_id])->find();

                if (!$order_item || empty($order_item)) {
                    write_log_record("订单添加失败6");
                    Db::rollback();
                    exception('订单添加失败');
                }

                //剩余本金
                $principal = $order_item['spent'];

                //剩余赠送金额
                $bonus = $order_item['gift'];

                $left_orderfee = 0;

                $insert_data = [];
                $update_data = [];
                
                if($order_item['consumption'] == 3) {//先消耗本金再消耗赠金
                    $res_data = $this->deductOrder($principal, $bonus, $order_price, 1);
                    $update_data = ['spent'=>$res_data['remaining_principal'],'gift'=>$res_data['remaining_bonus']];
                    $insert_data[] = ['card_type'=>$order_item['type'],'order_item_info_id'=>$card_id,'order_id'=>$order_id,'total'=>1,'createtime'=>time(),'type'=>1,'money'=>$res_data['deducted_principal']];
                    $insert_data[] = ['card_type'=>$order_item['type'],'order_item_info_id'=>$card_id,'order_id'=>$order_id,'total'=>1,'createtime'=>time(),'type'=>2,'money'=>$res_data['deducted_bonus']];
                    $order_deducted_fee = $res_data['deducted_principal'] + $res_data['deducted_bonus'];
                }elseif ($order_item['consumption'] == 4) {//先消耗赠金再消耗本金
                    $res_data = $this->deductOrder($principal, $bonus, $order_price, 2);
                    $update_data = ['spent'=>$res_data['remaining_principal'],'gift'=>$res_data['remaining_bonus']];
                    $insert_data[] = ['card_type'=>$order_item['type'],'order_item_info_id'=>$card_id,'order_id'=>$order_id,'total'=>1,'createtime'=>time(),'type'=>1,'money'=>$res_data['deducted_principal']];
                    $insert_data[] = ['card_type'=>$order_item['type'],'order_item_info_id'=>$card_id,'order_id'=>$order_id,'total'=>1,'createtime'=>time(),'type'=>2,'money'=>$res_data['deducted_bonus']];
                    $order_deducted_fee = $res_data['deducted_principal'] + $res_data['deducted_bonus'];
                }


                $consume_service=[];
                foreach ($orderInfo as $value){
                    $consume_service[]=$value['spec_name'];
                }
                //订单支付成功通知
                $spent = isset($update_data['spent']) ? $update_data['spent'] : 0;
                $gift = isset($update_data['gift']) ? $update_data['gift'] : 0;
                $push['card_pay_success'][]=[
                    'consume_service'=>join(',',$consume_service),
                    'order_price'=>$orderCount['totalfee'],
                    'time'=>date('Y-m-d H:i:s',time()),
                    'pay_way'=>'会员余额',
                    'balance'=> $spent + $gift,
                    'open_id'=>$userInfo['wechat_openid'],
                ];

                //更新充值卡数据
                $res = $this->order_item_model->where(['id'=>$card_id])->update($update_data);
                if(!$res || empty($res)){
                    write_log_record("订单添加失败7:".'更新数据'.var_export($update_data).'sql:'.$this->order_item_model->getLastSql());
                    Db::rollback();
                    exception('订单添加失败');
                }

                //卡项使用记录
                $res = $this->order_item_pay_model->insertAll($insert_data);
                if(!$res){
                    write_log_record("订单添加失败8");
                    Db::rollback();
                    exception('订单添加失败');
                }

                $res = $this->order_model->where('id',$order_id)->update(['carddiscount'=>$order_deducted_fee]);
            }

            //处理赠品
            if(isset($orderCount['giftdata']) && count($orderCount['giftdata']) > 0 && $orderCount['giftdata']>0){
                $giftdata = $orderCount['giftdata'];
                //赠送商品数据
                $goods_gift = [];
                $coupon_gift = [];

                //更新库存数量
                $goods_arr = [];
                $coupon_arr = [];

                foreach ($giftdata as $kgift => $vgift){
                    $vgift['number'] = (int)$vgift['number'];
                    if ($vgift['number'] > 0) {
                        //商品或服务
                        if (in_array($vgift['type'],[1,2])) {
                            $gift_goods_info = $this->goods_model->where(['id'=>$vgift['itemid']])->find();
                            $shop_info = $this->shop_model->where('id', $gift_goods_info['shop_id'])->find();
                            $where = [];
                            $where['goods_id'] = $vgift['itemid'];
                            $where['status'] = 'normal';
                            $where['state'] = '0';
                            $goods_sku_info = $this->goods_sku_model->where($where)->find();
                            if (!empty($gift_goods_info) && !empty($shop_info) && !empty($goods_sku_info)) {
                                $_goods_gift = [];
                                for ($j=0; $j < $vgift['number']; $j++) {
                                    $_goods_gift[] = [
                                        'order_id'          => $order_id,
                                        'goods_id'          => $vgift['itemid'],
                                        'shop_id'           => $gift_goods_info['shop_id'],
                                        'shop_name'         => $shop_info['shopname'],
                                        'title'             => $gift_goods_info['title'],
                                        'image'             => $gift_goods_info['image'],
                                        'goods_sku_sn'      => $goods_sku_info['sn'],
                                        'goods_sku_id'      => $goods_sku_info['id'],
                                        'difference'        => $goods_sku_info['difference'],
                                        'price'             => 0,
                                        'save_price'        => 0,
                                        'actual_payment'    => 0,
                                        'market_price'      => 0,
                                        'discount_price'    => 0,
                                        'number'            => 1,
                                        'createtime'        => time(),
                                        'staff_ids'         => '',
                                        'gdtype'            => $vgift['type'] == 1?'0':'1',
                                        'is_gift'           => '1',
                                        'validtime'         => isset($vgift['validtime']) && !empty(($vgift['validtime']))?strtotime($vgift['validtime']):2840112000,
                                    ];
                                }
                                unset($j);
                                $goods_gift = array_merge($_goods_gift,$goods_gift);

                                $goods_arr[] = ['id'=>$vgift['itemid'],'sales'=>$vgift['number'],'sku_id'=>$goods_sku_info['id']];
                            }
                        }else{//优惠券
                            $gift_coupon_info = $this->coupon_model->where(['id'=>$vgift['itemid']])->find();
                            $shop_info = $this->shop_model->where('id', $gift_coupon_info['shop_id'])->find();

                            if (!empty($gift_coupon_info) && !empty($shop_info)) {
                                for ($i=0; $i < $vgift['number']; $i++) {
                                    $coupon_gift[] = [
                                        'coupon_id'    => $vgift['itemid'],
                                        'coupon_no'    => Random::alnum(16),
                                        'user_id'      => $userInfo['id'],
                                        'shop_id'      => $shop_info['id'],
                                        'order_id'     => $order_id,
                                        'type'         => $gift_coupon_info['type'],
                                        'name'         => $gift_coupon_info['name'],
                                        'userlevel'    => $gift_coupon_info['userlevel'],
                                        'usertype'     => $gift_coupon_info['usertype'],
                                        'price'        => $gift_coupon_info['price'],
                                        'discount'     => $gift_coupon_info['discount'],
                                        'limit'        => $gift_coupon_info['limit'],
                                        'rangetype'    => $gift_coupon_info['rangetype'],
                                        'range'        => $gift_coupon_info['range'],
                                        'pretype'      => $gift_coupon_info['pretype'],
                                        'validity'     => $gift_coupon_info['validity'],
                                        'startdate'    => $gift_coupon_info['startdate'],
                                        'enddate'      => $gift_coupon_info['enddate'],
                                        'createtime'   => time(),
                                        'is_gift'      => '1',
                                    ];
                                }
                                $coupon_arr[] = ['id'=>$vgift['itemid'],'sales'=>$vgift['number'],'surplus'=>$gift_coupon_info['surplus'],'grant'=>$gift_coupon_info['grant']]; 
                            }
                        }
                    }
                }

                //处理商品、服务赠送
                if(count($goods_gift)>0){
                    $res = $this->goods_order_model->insertAll($goods_gift);
                    if(!$res){
                        write_log_record("订单添加失败26");
                        Db::rollback();
                        exception('订单添加失败');
                    }

                    //扣减商品或服务的库存
                    if(count($goods_arr)>0){
                        foreach ($goods_arr as $kstock => $vstock) {
                            $res1 = $this->goods_model->where(['id'=>$vstock['id']])->inc('sales', $vstock['sales'])->update();
                            $res2 = $this->goods_sku_model->where(['id'=>$vstock['sku_id']])->dec('stock', $vstock['sales'])->update();

                            if(!$res1 || !$res2){
                                write_log_record("订单添加失败27");
                                Db::rollback();
                                exception('订单添加失败');
                            }
                        }
                    }
                }

                //处理优惠券赠送
                if(count($coupon_gift)>0){
                    $res = $this->user_coupon_model->insertAll($coupon_gift);
                    if(!$res){
                        write_log_record("订单添加失败28");
                        Db::rollback();
                        exception('订单添加失败');
                    }

                    //扣减优惠券剩余数量
                    if(count($coupon_arr)>0){
                        foreach ($coupon_arr as $_kstock => $_vstock) {
                            $res1 = $res2 = true;
                            $res1 = $this->coupon_model
                                ->where(['id'=>$_vstock['id']])
                                ->inc('alreadygrant', $_vstock['sales'])
                                ->update();

                            if ($_vstock['grant'] != -1) {
                                $res2 = $this->coupon_model
                                ->where(['id'=>$_vstock['id']])
                                ->dec('surplus', $_vstock['sales'])
                                ->update();
                            }

                            if(!$res1 || !$res2){
                                write_log_record("订单添加失败28");
                                Db::rollback();
                                exception('订单添加失败');
                            }
                        }
                    }
                }
            }

            $goods_number = 0;
            if ($datatype == 'cards') {
                //卡项
                foreach ($orderInfo as $k => $v){
                    if ($v['cateid'] != 6) {
                        $card_info = $this->item_model->where('id', $v['spec_id'])->find();
                        if(!$card_info || empty($card_info) || $v['spec_number'] == 0){
                            write_log_record("订单添加失败9");
                            Db::rollback();
                            exception('订单添加失败');
                        }
                        $goods_number += $v['spec_number'];
                        for ($i=0; $i < $v['spec_number']; $i++) {
                            $item_data = [
                                'item_id' => $v['spec_id'],
                                'order_id' => $order_id,
                                'shop_id' => $this->shop_id,
                                'user_id' => $userInfo['id'],
                                'category_id' => $card_info['category_id'],
                                'type' =>$card_info['type'],
                                'name' => $card_info['name'],
                                'code' => $card_info['code'],
                                'consumption' => $card_info['consumption'],
                                'actual_price' => $v['spec_price'],
                                'save_price' => $v['spec_price'],
                                'price' => $card_info['price'],
                                'specs' => $card_info['specs'],
                                'image' => $card_info['image'],
                                'gift'  => $card_info['gift'],
                                'spent' => $v['spec_price'],
                                'total' => $v['spec_price'] + $card_info['gift'],
                                'validity' => $card_info['validity'],
                                'validitydays' => $card_info['validitydays'],
                                'shop_ids' => $card_info['shop_ids'],
                                'stock' => $card_info['stock'],
                                'activity' => $card_info['activity'],
                                'distribution' => $card_info['distribution'],
                                'flag'=> $card_info['flag'],
                                'activity_type' =>  $card_info['activity_type'],
                                'staff_ids'         => (isset($v['staff_ids']) && !empty($v['staff_ids']))?$v['staff_ids']:'',
                                'createtime' => time()
                            ];
                            if ($card_info['validity'] == 0){
                                $item_data['validitytime'] = 9999;
                            }
                            if ($card_info['validity'] == 1){
                                $item_data['validitytime'] = $card_info['validitytime'];
                            }
                            if ($card_info['validity'] == 2){
                                $item_data['validitytime'] = time() + $card_info['validitydays'] * 24 * 60 * 60;
                            }

                            if($item_data['type']==4){
                                //开卡成功通知
                                $push['card_success'][]=[
                                    'title'=>"恭喜您获得1张会员卡",
                                    'card_name'=>$item_data['name'],
                                    'price'=>$item_data['total'],
                                    'time'=>date('Y-m-d H:i:s',time()),
                                    'shop'=>$shopPo[$item_data['shop_id']]??"",
                                    'open_id'=>$userInfo['wechat_openid'],
                                ];
                                //充值成功
                                $push['recharge'][]=[
                                    'card_name'=>$item_data['name'],
                                    'recharge'=>$item_data['total'],
                                    'time'=>date('Y-m-d H:i:s',time()),
                                    'shop'=>$shopPo[$item_data['shop_id']]??"",
                                    'balance'=>$item_data['total'],
                                    'open_id'=>$userInfo['wechat_openid'],
                                ];
                            }elseif(in_array($item_data['type'],[1,2])){
                                $push['card_success'][]=[
                                    'title'=>"恭喜您获得1张会员卡",
                                    'card_name'=>$item_data['name'],
                                    'price'=>$item_data['total'],
                                    'time'=>date('Y-m-d H:i:s',time()),
                                    'shop'=>$shopPo[$item_data['shop_id']]??"",
                                    'open_id'=>$userInfo['wechat_openid'],
                                ];
                            }
                            //未付款时卡项状态为hidden，订单支付完成后更新卡项状态
                            if($order_data['state'] == 1){
                                $item_data['status'] = 'hidden';
                            }
                            $item_id =  $this->order_item_model->insertGetId($item_data);
                            if(!$item_id){
                                write_log_record("订单添加失败10");
                                Db::rollback();
                                exception('订单添加失败');
                            }

                            if ($card_info['type'] != 4) {
                                //`type` 卡项类型:1=有限次卡,2=不限次卡,3=通卡,4=充值卡,5=折扣卡
                                $sku_list = $this->item_info_model->where(['item_id' => $v['spec_id']])->select();

                                $total_fee = 0;
                                $all_total = 0;
                                foreach ($sku_list as $_kk => $_vv){
                                    $all_total += $_vv['total'];
                                    $sku_goods_info = $this->goods_sku_model->where(['goods_id'=>$_vv['goods_id'],'id'=>$_vv['sku_id']])->find();
                                    if ($sku_goods_info) {
                                        $total_fee += $sku_goods_info['price'] * $_vv['total']; 
                                    }
                                }

                                foreach ($sku_list as $kk => $vv){
                                    $sku_goods_info = $this->goods_sku_model->where(['goods_id'=>$_vv['goods_id'],'id'=>$_vv['sku_id']])->find();
                                    $item_info = [
                                        'order_item_id' => $item_id,
                                        'item_id' => $v['spec_id'],
                                        'order_id' => $order_id,
                                        'type' => $vv['type'],
                                        'goods_id' => $vv['goods_id'],
                                        'sku_id' => $vv['sku_id'],
                                        'total' => $vv['total'],
                                        'spent' => $vv['total'],
                                        'createtime' => time(),
                                    ];
                                    $item_info['price'] = number_format(($v['spec_price'] * ($vv['total']/$all_total))/$vv['total'], 2);
                                    //未付款时卡项状态为hidden，订单支付完成后更新卡项状态
                                    if($order_data['state'] == 1){
                                        $item_info['status'] = 'hidden';
                                    }
                                    $res = $this->order_item_info_model->insert($item_info);
                                    if(!$res || empty($res)){
                                    write_log_record("订单添加失败11");

                                        Db::rollback();
                                        exception('订单添加失败');
                                    }
                                }
                            }

                            if ($card_info['type'] == 1) {
                                $update_data = ['total'=>$all_total,'spent'=>$all_total];
                                $res = $this->order_item_model->where(['id'=>$item_id])->update($update_data);
                                // if(!$res || empty($res)){
                                //     Db::rollback();
                                //     exception('订单添加失败');
                                // }
                            }
                        }
                    }else{
                        //充值卡续费数据处理
                        $item_order_info = $this->order_item_model->where('id',$v['spec_id'])->find();
                        if(!$item_order_info){
                            write_log_record("原充值卡数据不存在");
                            Db::rollback();
                            exception('原充值卡数据不存在');
                        }
                        $item_data = [
                            'order_item_id'     => $v['spec_id'],
                            'order_id'          => $order_id,
                            'shop_id'           => $this->shop_id,
                            'user_id'           => $userInfo['id'],
                            'actual_price'      => $v['spec_price'],
                            'gift'              => $v['gift_price'],
                            'state'             => $order_data['state'] == 6?'2':'1',
                            'createtime'        => time(),
                            'updatetime'        => time(),
                            'staff_ids'         => (isset($v['staff_ids']) && !empty($v['staff_ids']))?$v['staff_ids']:0,
                        ];

                        $res = $this->order_item_recharge_model->insert($item_data);
                        if(!$res){
                            write_log_record("充值卡续费数据处理失败1");
                            Db::rollback();
                            exception('订单添加失败');
                        }

                        if($item_data['state'] == 2){//充值完成
                            $update_data = [];
                            $update_data['gift'] = sprintf("%.2f", $item_order_info['gift'] + $v['gift_price']);
                            $update_data['spent'] = sprintf("%.2f", $item_order_info['spent'] + $v['spec_price']);
                            $update_data['total'] = sprintf("%.2f", $item_order_info['total'] + $v['gift_price'] + $v['spec_price']);
                            $update_data['updatetime'] = time();

                            $res = $this->order_item_model->where('id',$v['spec_id'])->update($update_data);
                            if(!$res){
                                write_log_record("充值卡续费数据处理失败1");
                                Db::rollback();
                                exception('订单添加失败');
                            }
                        }
                        $res = $this->order_model->where('id',$order_id)->update(['isrecharge'=>1]);
                        // if(!$res){
                        //     write_log_record("充值卡续费数据处理失败2");
                        //     Db::rollback();
                        //     exception('订单添加失败');
                        // }
                    }
                }
            }else{

                //商品
                $order_num = 0;

                foreach ($orderInfo as $k => $_v){
                    $order_num += $_v['spec_number'];
                }
                foreach ($orderInfo as $k => $v){
                    $goods_info = $this->goods_model->where('id', $v['goods_id'])->find();
                    if(!$goods_info || empty($goods_info) || $v['spec_number'] == 0){
                        write_log_record("订单添加失败12");
                        Db::rollback();
                        exception('订单添加失败');
                    }
                    $goods_number += $v['spec_number'];
                    //更新商品销量
                    $sales = $goods_info['sales'] + $v['spec_number'];
                    $goods_update_data = ['sales'=>$sales,'updatetime'=>time()];
                    $res = $this->goods_model->where(['id'=>$v['goods_id']])->update($goods_update_data);
                    if(!$res || empty($res)){
                        write_log_record("订单添加失败13");
                        Db::rollback();
                        exception('订单添加失败');
                    }

                    //更新具体属性商品销量
                    $goods_sku_info = $this->goods_sku_model->where('id', $v['spec_id'])->find();
                    $shop_info = $this->shop_model->where('id', $goods_info['shop_id'])->find();
                    if(!$goods_sku_info || empty($goods_sku_info) || !$shop_info || empty($shop_info)){
                        write_log_record("订单添加失败14");
                        Db::rollback();
                        exception('订单添加失败');
                    }

                    $sku_sales = $goods_sku_info['sales'] + $v['spec_number'];
                    $sku_stock = $goods_sku_info['stock'] - $v['spec_number'];
                    if ($sku_stock < 0) {
                        Db::rollback();
                        exception('商品库存不足');
                    }

                    $goods_sku_update_data = ['stock'=>$sku_stock,'sales'=>$sku_sales,'updatetime'=>time()];
                    $res = $this->goods_sku_model->where(['id'=>$v['spec_id']])->update($goods_sku_update_data);
                    if(!$res || empty($res)){
                        write_log_record("订单添加失败15");
                        Db::rollback();
                        exception('订单添加失败');
                    }

                    $item_data = [
                        'order_id'          => $order_id,
                        'goods_id'          => $v['goods_id'],
                        'shop_id'           => $goods_info['shop_id'],
                        'shop_name'         => $shop_info['shopname'],
                        'title'             => $goods_info['title'],
                        'image'             => $goods_info['image'],
                        'goods_sku_sn'      => $goods_sku_info['sn'],
                        'goods_sku_id'      => $v['spec_id'],
                        'difference'        => $v['spec_name'],
                        'price'             => $v['spec_originalprice'],
                        'save_price'        => $v['spec_price'] * $v['spec_number'],
                        'actual_payment'    => $v['spec_price'] * $v['spec_number'],
                        'market_price'      => $v['spec_originalprice'],
                        'discount_price'    => $v['spec_originalprice'],
                        'number'            => $v['spec_number'],
                        'carddiscount'      => sprintf("%.2f",$order_deducted_fee/$order_num*$v['spec_number']),
                        'discount'          => sprintf("%.2f",$orderCount['discount']/$order_num*$v['spec_number']),
                        'createtime'        => $orderCount['issupplement'] == 1?strtotime($orderCount['supplementtime']):time(),
                        'staff_ids'         => (isset($v['staff_ids']) && !empty($v['staff_ids']))?$v['staff_ids']:'',
                        'gdtype'            => $v['datatype'] == 'goods'?0:1,
                    ];
                    //$item_data['actual_payment'] = $item_data['actual_payment'] - $item_data['carddiscount'] - $item_data['discount'];
                    //$item_data['actual_payment'] = $item_data['actual_payment'] > 0?$item_data['actual_payment']:0;
                    $card_num = 0;
                    $itemPayId=[];
                    $_item_data = $item_data;
                    if (isset($v['cards']) && count($v['cards'])>0) {
                        $insert_data = [];
                        foreach($v['cards'] as $key => $val){

                            // //获取可用的卡项,通过sku_id获取goods_id,进而获取当前商品铺设的店铺里面的商品
                            // $goods_id = $this->goods_sku_model->where(['id'=>$v['spec_id']])->value('goods_id');
                            // $_goods_id = $goods_id;
                            // $goods_ids = [];
                            // if ($this->shop_id != 1) {
                            //     $_goods_id = $this->goods_shop_model->where(['new_goods_id'=>$goods_id])->value('goods_id');
                            // }

                            // $goods_ids = $this->goods_shop_model->where(['goods_id'=>$_goods_id])->column('new_goods_id');

                            // $goods_ids = array_unique(array_merge($goods_ids, [$_goods_id]));


                            //卡项详情
                            $order_item_info = $this->order_item_info_model->where(['id'=>$key])->find();

                            $order_item = $this->order_item_model->where(['id'=>$order_item_info['order_item_id']])->find();


                            //更新卡项剩余次数
                            $order_item['spent'] = (int)$order_item['spent'] - $val;
                            $res = $this->order_item_model->where(['id'=>$order_item['id']])->update(['spent'=>$order_item['spent']]);
 
                            if(!$res){
                                write_log_record("订单添加失败16");
                                Db::rollback();
                                exception('订单添加失败');
                            }
                            //更新卡项商品剩余次数
                            $order_item_info['spent'] = (int)$order_item_info['spent'] - $val;

                            $res = $this->order_item_info_model->where(['id'=>$key])->update(['spent'=>$order_item_info['spent']]);
                            
                            if(!$res){
                                write_log_record("订单添加失败17:".$this->order_item_info_model->getLastSql());
                                write_log_record("订单添加失败17");
                                Db::rollback();
                                exception('订单添加失败');
                            }
                            $card_num += $val;
                            $createtime = $orderCount['issupplement'] == 1?strtotime($orderCount['supplementtime']):time();
                            $push['times_card_pay_success'][0]=[
                                'shop_name'=>$shopPo[$this->shop_id]??"",
                                'pay_way'=>'会员权益',
                                'use_times'=>$card_num,
                                'open_id'=>$userInfo['wechat_openid'],
                            ];
                            unset($push['shop_card_times_success']);
                            $insert_data[] = ['card_type'=>$order_item['type'],'money'=>$v['uprice'],'order_item_info_id'=>$key,'order_id'=>$order_id,'total'=>$val,'createtime'=>$createtime];
                        }
                        //卡项使用记录

                        if($insert_data){
                            foreach ($insert_data as $valPay){
                                $res = $this->order_item_pay_model->insertGetId($valPay);
                                if(!$res){
                                    write_log_record("订单添加失败18");
                                    Db::rollback();
                                    exception('订单添加失败');
                                }else{
                                    $itemPayId[]=$res;
                                }
                            }

                        }


                    }

                    //使用权益卡
                    if ($card_num > 0 ) {
                        $item_data['actual_payment'] = 0;
                        $item_data['number'] = $card_num;
                        $item_res =  $this->goods_order_model->insertGetId($item_data);

                        if(!$item_res){
                            write_log_record("订单添加失败19");
                            Db::rollback();
                            exception('订单添加失败');
                        }else{
                            if($itemPayId){
                                $this->order_item_pay_model->where('id','in',$itemPayId)->update(['order_goods_id'=>$item_res]);
                            }
                        }
                    }

                    //剩余未使用权益卡的商品
                    if ($v['spec_number'] > $card_num) {
                        $_item_data['number'] = $v['spec_number'] - $card_num;
                        $_item_res =  $this->goods_order_model->insert($_item_data);
                    
                        if(!$_item_res){
                            write_log_record("订单添加失败20");
                            Db::rollback();
                            exception('订单添加失败');
                        }
                    }
                }
            }

            //订单支付表日志
            foreach ($payInfo as $pkey3 => $pvalue3) {
                $pay_log_data = [];
                $pay_log_data['pay_no'] = date("Ymdhis") . sprintf("%08d", $userInfo['id']) . mt_rand(1000, 9999);
                $pay_log_data['trade_no'] = date('YmdHis'). rand(10000000,99999999). substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
                $pay_log_data['user_id'] = $userInfo['id'];
                $pay_log_data['shop_id'] = $this->shop_id;
                $pay_log_data['order_id'] = $order_id;
                $pay_log_data['order_no'] = $order_no;

                $pay_type = '0';
                $pay_state = '1';
                if ($pvalue3['id'] == 10) {
                    $pay_type = '1';
                    $pay_state = '0';
                }elseif ($pvalue3['id'] == 12) {
                    $pay_state = '0';
                }

                $pay_log_data['pay_type'] = $pay_type;
                $pay_log_data['pay_state'] = $pay_state;
                $pay_log_data['number'] = $goods_number;
                $pay_log_data['price'] = $actual_price;
                $pay_log_data['order_price'] = $actual_price;
                $pay_log_data['freight_price'] = 0;
                $pay_log_data['coupon_price'] = $orderCount['discount'];
                $pay_log_data['discount_price'] = $orderCount['discount'];
                $pay_log_data['actual_payment'] = $pvalue3['amount'];
                $pay_log_data['total_amount'] = $actual_price;
                $pay_log_data['pay_way_id'] = $pvalue3['id'];
                $pay_log_data['notice'] = '收银台订单，订单编号：'.$order_no;
                $pay_log_data['createtime'] = time();
                $pay_id = $this->wanlshop_pay_model->insertGetId($pay_log_data);

                if(!$pay_id || empty($pay_id)){
                    write_log_record("订单添加失败21");
                    Db::rollback();
                    exception('订单添加失败');
                }

                //处理支付方式
                $trade_data = ['out_trade_no'=>'','pay_id'=>$pay_id,'pay_way_id'=>$pvalue3['id'],'order_id'=>$order_id,'price'=>$pvalue3['amount'],'createtime'=>time()];
                $res = $this->pay_out_trade_model->insert($trade_data);

                if(!$res || empty($res)){
                    write_log_record("订单添加失败22");
                    Db::rollback();
                    exception('订单添加失败');
                }

            }


            //返回数据
            $return_data = ['order_id'=>$order_id,'order_no'=>$order_no];
            //生成支付二维码
            if (!empty($cur_pay_type)) {
                $req_url = cdnurl('/api/Pay/consume',true);//拉卡拉消费接口

                $back_url = cdnurl('/api/Member/syncorder',true);//后台支付回调链接
                $amount = sprintf("%d",$cur_pay_amount * 100);
                //请求参数
                $req_params = [
                    'seller_member_no'      => Config::get('lal_config.member_no'),                 // 卖家标识
                    'out_order_no'          => 'no_'. $order_no,                                    // 应用平台订单号（唯一的）
                    'amount'                => $amount,                                             // 订单金额（单位：分）
                    'pay_amount'            => $amount,                                             // 首次支付金额（单位：分）
                    'terminal_ip'           => $this->request->ip(),                                // 终端IP
                    'order_name'            => 'no_'. $order_no,                                    // 订单名称
                    'split_mode'            => 0,                                                   // 分账模式
                    'back_url'              => $back_url,                                           // 后台通知地址 
                ];

                // 支付方式
                $req_params['pay_method']     = ['GATEWAY' => [
                    'member_no'             => Config::get('lal_config.member_no'),                         // 卖家标识
                    'merchant_no'           => Config::get('lal_config.merchant_no'),                       // 钱帐通商户号                                     
                    'amount'                => $amount,                              // 支付金额，单位：分   
                    'product_name'          => '订单('.$order_no.')的商品'.Random::alnum(),
                    'inte_routing'          => 1,
                ]];

                // $req_params['pay_method']['GATEWAY']['counter_param']['pay_mode'] = 'WECHAT';
                // if($orderCount['pay_way_id'] == 11){
                //     $req_params['pay_method']['GATEWAY']['counter_param']['pay_mode'] = 'ALIPAY';
                // }

                if ($cur_pay_type == 'scan') {
                    // 支付方式
                    $req_params['pay_method']     = ['SCAN' => [
                        'bar_code'              => $scanresult,
                        'app_id'                => Config::get('lal_config.c_mch_appid'),
                        'amount'                => $amount,
                        'subject'               => '购买商品'.Random::alnum(),
                        'member_no'             => Config::get('lal_config.member_no'),
                        'merchant_no'           => Config::get('lal_config.j_merchant_no'),
                        'term_base_station'     => $this->request->ip(),
                    ]];
                    //获取经纬度
                    $geoData = getGeoLocationByIP($this->request->ip());
                    if (!empty($geoData['lat']) && !empty($geoData['lon'])) {
                        $req_params['pay_method']['SCAN']['term_loc'] = '+'.$geoData['lat'].'/'.'+'.$geoData['lon'];
                    }

                }
                

                // 分账规则
                // if ($shop_info['open_split'] == 1) {
                //     $commission = sprintf("%d",$amount * 0.99);//佣金
                //     $left_commission = sprintf("%d",$amount - $commission);

                //     if ($commission == $amount) {
                //         $req_params['split_rule_data']= ['split_list' => [
                //             ['member_no' => Config::get('lal_config.member_no'), 'amount' => $amount],
                //         ]];
                //     }else{
                //         $req_params['split_rule_data']= ['split_list' => [
                //             ['member_no' => Config::get('lal_config.member_no'), 'amount' => $commission, 'special_account_no' => 'S005'],    // S005分到商户佣金专用账户，仅商户会员
                //             ['member_no' => Config::get('lal_config.member_no'), 'amount' => $left_commission],
                //         ]];
                //     }
                // }

                write_log_record("支付请求参数：".json_encode($req_params));

                $result = send_request($req_url, json_encode($req_params),'POST');
                if(!$result && empty($result)){
                    write_log_record("订单添加失败23");
                    Db::rollback();
                    exception('订单添加失败');
                }

                write_log_record("支付请求结果：".json_encode($result));

                if ($result['data']['status'] == 'ERROR') {
                    write_log_record("订单添加失败24");
                    Db::rollback();
                    exception('订单添加失败');
                }

                if ($cur_pay_type == 'qrcode' && isset($result['data']['result']['pay_info']['counter_url']) && !empty($result['data']['result']['pay_info']['counter_url'])) {
                    $return_data['qrcode_url'] = $result['data']['result']['pay_info']['counter_url'];
                }
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            write_log_record("[".date("Y-m-d H:i:s")."]生成订单错误行数：".$e->getLine());
            write_log_record("[".date("Y-m-d H:i:s")."]生成订单错误文件：".$e->getFile());
            write_log_record("[".date("Y-m-d H:i:s")."]生成订单错误信息：".$e->getMessage());
            // return $this->error($e->getMessage());
            write_log_record("订单添加失败25");
            return $this->error('订单添加失败');
        }
        write_log_record("订单添加成功,结果：".json_encode($return_data));
        $this->pushMsg($order_id,$push,$order_data['state']);
        return $this->success('订单添加成功！','',$return_data);
    }

    public function pushMsg($orderId,$push,$orderState=1){
        write_log_record("推送消息,内容：".json_encode($push));
        if($push){
            if($orderState==6){
                $temp =\config('msg_template');

                $url = cdnurl('/api/Weixin/sentMsg',true);//拉卡拉退款接口
                foreach ($push as $key=>$value){
                    if($key=='card_success'){
                        foreach ($value as $val){
                            $content=$temp[$key]['content'];
                            $content['thing7']['value'] =$val['title'];
                            $content['thing10']['value'] =$val['card_name'];
                            $content['amount4']['value'] =sprintf('%.2f',$val['price']);
                            $content['time1']['value'] =$val['time'];
                            $content['thing6']['value'] =$val['shop'];
                            $param=[];
                            $param['template_id']=$temp[$key]['template_id'];
                            $param['content']=json_encode($content);
                            $param['open_id']=$val['open_id'];
                            $result = curlPost($url,$param);

                        }

                    }elseif ($key=='recharge'){
                        foreach ($value as $val){
                            $content=$temp[$key]['content'];
                            $content['thing10']['value'] =$val['shop'];
                            $content['thing11']['value'] =$val['card_name'];
                            $content['amount2']['value'] =sprintf('%.2f',$val['recharge']);
                            $content['time4']['value'] =$val['time'];
                            $content['amount3']['value'] =sprintf('%.2f',$val['balance']);
                            $param=[];
                            $param['template_id']=$temp[$key]['template_id'];
                            $param['content']=json_encode($content);
                            $param['open_id']=$val['open_id'];
                            $result = curlPost($url, $param);

                        }

                    }elseif ($key=='shop_card_times_success'){
                        foreach ($value as $val){
                            $content=$temp[$key]['content'];
                            $content['amount4']['value'] =sprintf('%.2f',$val['order_price']);
                            $content['time11']['value'] =$val['time'];

                            $param=[];
                            $param['template_id']=$temp[$key]['template_id'];
                            $param['content']=json_encode($content);
                            $param['open_id']=$val['open_id'];
                            $result = curlPost($url, $param);

                        }
                    }elseif ($key==='times_card_pay_success'){
                        //'shop_name'=>$shopPo[$this->shop_id]??"",
                        //                                'pay_way'=>'会员权益',
                        //                                'use_times'=>$val + $push['times_card_pay_success'][$key]['use_times'],
                        foreach ($value as $val){
                            $content=$temp[$key]['content'];
                            $content['thing12']['value'] =$val['shop_name'];
                            $content['thing9']['value'] ="本次耗卡{$val['use_times']}次";
                            $content['phrase8']['value'] =$val['pay_way'];

                            $param=[];
                            $param['template_id']=$temp[$key]['template_id'];
                            $param['content']=json_encode($content);
                            $param['open_id']=$val['open_id'];
                            $result = curlPost($url, $param);

                        }
                    }elseif ($key==='card_pay_success'){
                        //'consume_service'=>join(',',$consume_service),
                        //                    'order_price'=>$orderCount['totalfee'],
                        //                    'time'=>date('Y-m-d H:i:s',time()),
                        //                    'pay_way'=>'会员余额',
                        //                    'balance'=>$update_data['spent'] + $update_data['gift'],
                        foreach ($value as $val){
                            $content=$temp[$key]['content'];
                            $content['thing13']['value'] =$val['consume_service'];
                            $content['amount4']['value'] =sprintf('%.2f',$val['order_price']);
                            $content['time5']['value'] =$val['time'];
                            $content['phrase8']['value'] =$val['pay_way'];
                            $content['amount14']['value'] =sprintf('%.2f',$val['balance']);

                            $param=[];
                            $param['template_id']=$temp[$key]['template_id'];
                            $param['content']=json_encode($content);
                            $param['open_id']=$val['open_id'];
                            $result = curlPost($url, $param);

                        }
                    }
                    write_log_record("推送消息,结果：".json_encode($result));
                }
            }else{
                $tmp=[];
                $tmp['order_id'] =$orderId;
                $tmp['content'] =json_encode($push);
                $tmp['state'] =0;
                $tmp['createtime'] =time();
                Db::name('order_push_msg')->insert($tmp);
            }
        }
    }
    //检测订单状态
    public function checkorderstatus(){
        if (true === $this->request->isAjax()) {
            $order_no = $this->request->param('order_no','');
            if (!$order_no || empty($order_no)) {
                return $this->error('订单信息不存在');
            }
            $order_info = $this->order_model->where(['order_no'=>$order_no])->find();
            if (!$order_info || empty($order_info)) {
                return $this->error('订单信息不存在');
            }

            if ($order_info['state'] != 6) {
                return $this->error('当前订单还未支付！');
            }

            return $this->success('订单支付成功','',['order_no'=>$order_no,'time'=>date('Y-m-d H:i:s')]);
        }
        return $this->error('非法请求，请稍后重试');
    }

    //订单赠送
    public function getDataList(){
        $limit = 6;
        $list = [];
        if (true === $this->request->isAjax()) {
            $page = $this->request->param('page',1);
            $cateid = $this->request->param('cateid',0);
            $searchword = trim($this->request->param('searchword',''));
            $type = $this->request->param('type',1);//goods/services/cards
            $list = [];
            $condition = [];
            $condition['shop_id'] = $this->shop_id;

            if (in_array($type,[1,2])) {
                if ($cateid != 0) {
                    $condition['category_id'] = $cateid;
                }
                $condition['goods.status'] = 'normal';
                $condition['goods.grounding'] = '1';
                $condition['goods.gdtype'] = $type == 1?'0':'1';
                $condition['goods.publishing_platform'] = ['in',['0','2']];
                if (!empty($searchword)) {
                    $condition['title'] = ['like','%'.$searchword.'%'];
                }

                $list = $this->goods_model
                    ->field('id,image,title,price,createtime')
                    ->with('category')
                    ->where($condition)
                    ->paginate($limit, false, ['page' => $page])
                    ->each(function ($v) {
                        $v['image'] = get_img($v['image']);
                        return $v;
                    })->toArray();
                if ($list['total'] > 0) {
                    foreach ($list['data'] as $key => &$value) {
                        $value['cate_name'] = $value['category']['name'];
                        $value['createtime'] = date('Y-m-d H:i:s',$value['createtime']);
                    }
                }
            }else{
                switch ($cateid) {
                    case 1:
                        $condition['type'] = 'reduction';
                        break;
                    case 2:
                        $condition['type'] = 'discount';
                        break;
                    case 3:
                        $condition['type'] = 'shipping';
                        break;
                    case 4:
                        $condition['type'] = 'vip';
                        break;
                    default:
                        $condition['type'] = 'reduction';
                        break;
                }

                $condition['surplus'] = ['>',0];
                $condition['enddate'] = ['>=',date('Y-m-d')];
                if (!empty($searchword)) {
                    $condition['searchword'] = ['like','%'.$searchword.'%'];
                }

                $list = $this->coupon_model
                    ->field('id,name as title,type,price,createtime')
                    ->where($condition)
                    ->whereNull('deletetime')
                    ->paginate($limit, false, ['page' => $page])
                    ->toArray();

                if ($list['total'] > 0) {
                    foreach ($list['data'] as $key => &$value) {
                        $value['createtime'] = date('Y-m-d H:i:s',$value['createtime']);
                        $value['price'] = '-';
                        switch ($cateid) {
                            case 1:
                                $value['cate_name'] = '现金券';
                                break;
                            case 2:
                                $value['cate_name'] = '折扣券';
                                break;
                            case 3:
                                $value['cate_name'] = '兑换券';
                                break;
                            case 4:
                                $value['cate_name'] = '体验券';
                                break;
                            default:
                                $value['cate_name'] = '现金券';
                                break;
                        }
                    }
                }
            }
        }
        return $this->success('', '', $list);
    }

    public function getcategory()
    {
        $type = $this->request->param('type');
        $category = [];
        $category[] = ['id'=>1,'name'=>'现金券'];
        $category[] = ['id'=>2,'name'=>'折扣券'];
        $category[] = ['id'=>3,'name'=>'兑换券'];
        $category[] = ['id'=>4,'name'=>'体验券'];
        if (in_array($type,[1,2])) {
            $pid = $type == 1?$this->goods_pid:$this->service_pid;
            $where = [];
            $where['pid'] = $pid;
            $where['status'] = 'normal';
            $where['publishing_platform'] = ['in',['0','2']];
            $category = $this->goods_category_model->field('id,name')->where($where)->select();
        }
        
        return $this->success('', '', $category);
    }

    public function notice()
    {
        return $this->view->fetch();
    }
}
